package com.example.mydownloader.netty.inBound

import com.example.mydownloader.mymodule.encrypt.AESCryptUtil
import com.example.mydownloader.mymodule.gson.GsonUtil
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.netty.NettyManager
import com.example.mydownloader.netty.NettyMsg
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

/**
 * @Description:
 * Netty消息解密处理
 * @author Wallace
 * @Date 2022/2/14 9:34
 */
class NettyMsgDecryptHandler : SimpleChannelInboundHandler<ByteArray>() {

    private val aesKey = NettyManager.aesKey

    override fun channelRegistered(ctx: ChannelHandlerContext?) {
        LogUtil.i("Netty通道已注册，服务端[${ctx?.channel()?.remoteAddress()}]")
        ctx?.fireChannelRegistered()
    }

    override fun channelRead0(ctx: ChannelHandlerContext?, msg: ByteArray?) {
        LogUtil.d("msg = ${msg?.toString(Charsets.UTF_8)}")
        val plainByteArray =
            msg?.let { AESCryptUtil.decryptAfterDecode(it, aesKey!!.getSecretKeySpec(), aesKey.iv) }
        if (plainByteArray?.isNotEmpty() == true) {
            val jsonString = plainByteArray.toString(Charsets.UTF_8)
            val nettyMsg = GsonUtil.toAny(jsonString, NettyMsg::class.java)
            nettyMsg?.let {
                LogUtil.i("receive message from server[${ctx?.channel()?.remoteAddress()}] : $it")
                // 消息传递给下一个handler
                ctx?.fireChannelRead(it)
            }
        }else{
            LogUtil.w("fail to decrypt")
        }
    }
}